package com.our.sys.project1.service;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.our.set.entity.User;
import com.our.set.service.CommonService;
import com.our.sys.project1.CodeUtils;
import com.our.sys.project1.RunConstants;
import com.our.sys.project1.dao.PersonDao;
import com.our.sys.project1.dao.ReadyCodeDao;
import com.our.sys.project1.dao.ReadySendDao;
import com.our.sys.project1.entity.Person;
import com.our.sys.project1.entity.ReadyCode;
import com.our.sys.project1.entity.ReadySend;

@Service
@Transactional
public class ReadyCodeService {

    @Autowired
    private ReadyCodeDao readyCodeDao;

    @Autowired
    private ReadySendDao readySendDao;

    @Autowired
    private CommonService commonService;

    @Autowired
    private PersonDao personDao;

    private static Logger logger = LoggerFactory.getLogger(ReadyCodeService.class);

    @Transactional(readOnly = true)
    public Page<ReadyCode> query(Page<ReadyCode> page, List<PropertyFilter> filters) {
        Page<ReadyCode> curPage = readyCodeDao.findPage(page, filters);
        return curPage;
    }

    @Transactional(readOnly = true)
    public Page<ReadySend> querySend(Page<ReadySend> page, List<PropertyFilter> filters) {
        Page<ReadySend> curPage = readySendDao.findPage(page, filters);
        return curPage;
    }

    @Transactional(readOnly = true)
    public List<ReadyCode> queryList(Map<String, Object> map) {
        StringBuffer hql = new StringBuffer(500);
        String name = (String) map.get("2");
        Long readySendId = (Long) map.get("3");
        hql.append("from ReadyCode where 1=1 and readyCodeState = ?1");
        if (StringUtils.isNotBlank(name))
            hql.append(" and (supplierName like ?2 or materialName like ?2 or factoryCode like = ?2)");
        if (null != readySendId)
            hql.append(" and readySendId = ?3");
        List<ReadyCode> curPage = readyCodeDao.find(hql.toString(), map);
        return curPage;
    }

    public void save(ReadyCode rc, User u) throws Exception {
        try {
            rc.setReadyCodeTime(commonService.getNowString());
            rc.setReadyCodeWho(u.getName());
            rc.setReadyCodeState(RunConstants.READY_CODE);
            readyCodeDao.save(rc);
            rc.setReadyUId(rc.getId());
            rc.setReadyCodeNumber(1L);
            String systime = String.valueOf(System.currentTimeMillis());
            String code = systime.substring(4, 13);
            rc.setManagerCode(code);
            //String fileName = code + ".jpg";
            //生成图片，并保存
            //CodeUtils.generateCode128Barcode(new File("C:/hrp_system/code_img/" + fileName), code);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    public String printCode(String codes, String clazzPath) throws Exception {
        StringBuffer sb = new StringBuffer(1000);
        sb.append("<html><body>");
        try {
            String[] codeStrs = codes.split(",");
            for (String code : codeStrs) {
                String fileName = code + ".jpg";
                //生成图片，并保存
                CodeUtils.generateCode128Barcode(new File(clazzPath + "/" + fileName), code);

                //组装HTML
                sb.append("<img src=\"http://localhost:8089/sshapp/resources/img/codeimg/" + fileName + "?id="
                        + System.currentTimeMillis() + "\"/>");
            }
            sb.append("</body></html>");
            return sb.toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    public void saveAg(Long id, String endTime, User u) throws Exception {
        try {
            ReadyCode thisRc = readyCodeDao.findOneBy("id", id);
            ReadyCode rc = readyCodeDao.findOneBy("id", thisRc.getReadyUId());
            ReadyCode newRc = new ReadyCode();
            newRc.setMaterialId(rc.getMaterialId());
            newRc.setSupplierId(rc.getSupplierId());
            newRc.setReadyCodeTime(commonService.getNowString());
            newRc.setReadyCodeWho(u.getName());
            newRc.setReadyCodeState(RunConstants.READY_CODE);
            String endTimestr = "";
            if (endTime.indexOf("T") > 0) {
                endTimestr = endTime.substring(0, endTime.indexOf("T"));
                if (endTimestr.indexOf("-") > 0) {
                    endTimestr = endTimestr.replace("-", ".");
                }

            } else {
                if (endTime.indexOf("-") > 0) {
                    endTimestr = endTime.replace("-", ".");
                }
            }
            newRc.setEndTime(endTimestr);

            readyCodeDao.save(newRc);
            List<ReadyCode> rcList = readyCodeDao.find("from ReadyCode where readyUId = ? order by readyCodeNumber",
                    rc.getId());
            ReadyCode getReadyCode = rcList.get(rcList.size() - 1);
            newRc.setReadyUId(rc.getId());
            newRc.setReadyCodeNumber(getReadyCode.getReadyCodeNumber() + 1);
            String systime = String.valueOf(System.currentTimeMillis());
            String code = systime.substring(4, 13);
            newRc.setManagerCode(code);
            //String fileName = code + ".jpg";
            //生成图片，并保存
            //CodeUtils.generateCode128Barcode(new File("C:/hrp_system/code_img/" + fileName), code);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    public void cancel(Long id, User u) throws Exception {
        ReadyCode rc = readyCodeDao.findOneBy("id", id);
        if (Long.valueOf(rc.getReadyCodeState()).compareTo(0L) > 0) {
            throw new Exception("未处于备码状态的记录，不能取消备码！请联系管理员！");
        }
        try {
            rc.setReadyCodeState(RunConstants.READY_CANCEL);
            rc.setCancelCodeTime(commonService.getNowString());
            rc.setCancelCodeWho(u.getName());
            readyCodeDao.save(rc);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    public void readyGoods(Long id, String code, User u) throws Exception {
        ReadyCode rc = readyCodeDao.findOneBy("id", id);
        try {
            rc.setFactoryCode(code);
            rc.setReadyGoodsWho(u.getName());
            rc.setReadyGoodsTime(commonService.getNowString());
            rc.setReadyCodeState(RunConstants.READY_GOODS);
            readyCodeDao.save(rc);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    public void saveSend(String number, String ids, User u, String flag, String docName, String actionRoom,
            String tofficesId, String num) throws Exception {
        try {
            ReadySend readySend = new ReadySend();
            if (flag.equals(RunConstants.READY_SEND_NONEED)) {
                Person person = personDao.findOneBy("number", number);
                readySend.setPersonId(person.getId());
            }
            readySend.setDocName(docName);
            readySend.setActionRoom(actionRoom);
            readySend.setTofficesId(StringUtils.isBlank(tofficesId) ? null : Long.valueOf(tofficesId));
            readySend.setNum(num);
            readySend.setState(flag);
            readySend.setReadySendTime(commonService.getNowString());
            readySend.setReadySendWho(u.getName());
            readySendDao.save(readySend);
            Long readySendId = readySend.getId();

            String[] tempId = ids.split(",");
            for (String id : tempId) {
                ReadyCode readyCode = readyCodeDao.findOneBy("id", Long.valueOf(id));
                readyCode.setReadySendId(readySendId);
                readyCode.setReadyCodeState(RunConstants.READY_SEND);
                readyCodeDao.save(readyCode);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    public void saveReSend(String number, Long rId) throws Exception {
        try {
            ReadySend readySend = readySendDao.findOneBy("id", rId);
            Person person = personDao.findOneBy("number", number);
            readySend.setPersonId(person.getId());
            readySend.setState(RunConstants.READY_SEND_NONEED);
            readySendDao.save(readySend);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    @Transactional(readOnly = true)
    public List<ReadyCode> queryListBySendId(Long id) {
        return readySendDao.find("from ReadyCode where readySendId = ?", id);
    }
}
